﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Chowpoo.Common;
using Chowpoo.Util;
using CourseSystem.Common;
using CourseSystem.Common.Helpers;
using CourseSystem.Core.BLL;
using CourseSystem.Core.Entities;
using CourseSystem.Core.Enum;
using CourseSystem.Stat.ActionFilter;
using Webdiyer.WebControls.Mvc;

namespace CourseSystem.Web.Controllers
{
    [UserAuth(UserType = UserTypeEnum.Teacher)]
    public class AdminExamLibController : BaseController
    {
        [UrlStatFilter]
        public ActionResult Lib()
        {
            return View();
        }
        [UrlStatFilter]
        public ActionResult Examiner()
        {
            return View();
        }

        public ActionResult ExamWarnAll(int eid)
        {
            if (ExamStatusBLL.SetWarnAll(eid))
            {
                SetAlertMsg("全体警告成功!", true);
            }
            return RedirectToAction("ExamStatus", new { eid });
        }

        public ActionResult ExamEnforceAll(int eid)
        {
            if (ExamStatusBLL.SetEnforceSubmitAll(eid))
            {
                SetAlertMsg("全体强制交卷成功!", true);
            }
            return RedirectToAction("ExamStatus", new { eid });
        }

        public ActionResult ExaminerListUc(int? pid, string title)
        {
            var now = DateTime.Now;
            CommonRequest.ClearCache();
            var list = ExaminationBLL.GetList(4, title).Where(o => o.StartTime <= now && o.EndTime >= now).OrderByDescending(o => o.Id);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView(model);
        }

        public ActionResult ExamWarn(int id)
        {
            var info = ExamStatusBLL.Get(id);
            if (info == null)
                return NotFound();
            if (!info.IsWarning)
            {
                info.IsWarning = true;
                if (ExamStatusBLL.Edit(info))
                {
                    SetAlertMsg("警告成功!", true);
                    return RedirectToAction("ExamStatus", new { eid = info.Eid });
                }
                SetAlertMsg("警告失败!", true);
                return RedirectToAction("ExamStatus", new { eid = info.Eid });
            }
            SetAlertMsg("警告成功!", true);
            return RedirectToAction("ExamStatus", new { eid = info.Eid });
        }

        public ActionResult ExamStatusListUc(int? pid, int eid, string name, string uid)
        {
            CommonRequest.ClearCache();
            var list = ExamStatusBLL.GetList(eid, name, uid).OrderByDescending(o => o.Id);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView(model);
        }

        public ActionResult ExamStatus(int eid)
        {
            var info = ExaminationBLL.Get(eid);
            if (info == null)
                return NotFound();
            var list = ExamStatusBLL.GetList(eid);
            ViewData["doing"] = list.Count(o => o.Status == 0);
            ViewData["done"] = list.Count(o => o.Status == 1);
            return View(info);
        }

        public ActionResult SectionTestEditUc(int id)
        {
            var info = ExaminationBLL.Get(id);
            if (info == null)
                return NotFound();
            return PartialView(info);
        }
        [HttpPost]
        public ActionResult SectionTestEditUc(ExaminationInfo info)
        {
            if (info.Id == 0)
                return NotFound();
            ViewData.Model = info;
            if (!ModelState.IsValid)
                return PartialView();
            var oldInfo = ExaminationBLL.Get(info.Id);
            if (oldInfo == null)
                return NotFound();
            if (oldInfo.Type == 0)
            {
                oldInfo.LimitTime = info.LimitTime;
            }
            else if (oldInfo.Type == 1)
                oldInfo.EndTime = info.EndTime;
            if (ExaminationBLL.Edit(oldInfo))
            {
                SetHighLineMsg("编辑成功.");
                return PartialView(oldInfo);
            }
            SetHighLineMsg("未知错误.");
            return PartialView();
        }

        public ActionResult ExaminationEditUc(int? id)
        {
            if (id.HasValue)
            {
                var oldInfo = ExaminationBLL.Get(id.Value);
                if (oldInfo == null)
                    return NotFound();
                if (oldInfo.Type != 4)
                    return NotFound();
                oldInfo.CollegeIdFake = oldInfo.ClassInfo.SubjectInfo.DepartmentInfo.CollegeId;
                oldInfo.DepartmentIdFake = oldInfo.ClassInfo.SubjectInfo.DepartId;
                oldInfo.SubjectIdFake = oldInfo.ClassInfo.SubjectId;
                return PartialView(oldInfo);
            }
            return PartialView(new ExaminationInfo { StartTime = DateTime.Now, EndTime = DateTime.Now.AddDays(2) });
        }


        [HttpPost]
        public ActionResult ExaminationEditUc(ExaminationInfo info)
        {
            ViewData.Model = info;
            if (string.IsNullOrEmpty(info.Title))
                ModelState.AddModelError("Title", "必须填写");
            if (info.ClassId == 0)
                ModelState.AddModelError("ClassId", "请选择");
            if (info.YearId == 0)
                ModelState.AddModelError("YearId", "请选择");
            if (!ModelState.IsValid)
                return PartialView();
            var isBukao = info.Title.Contains("补考");
            var isCan = ExaminationBLL.CheckCanAddExam(info.ClassId, info.YearId, isBukao, info.Id);
            if (!isCan)
            {
                if (isBukao)
                    SetHighLineMsg("不能创建补考试卷！每个班每个年级只能创建一份普通试卷与补考试卷！");
                else
                    SetHighLineMsg("不能创建多于一份普通试卷！每个班每个年级只能创建一份普通试卷与补考试卷！");
                return PartialView(info);
            }
            if (info.Id != 0)
            {
                var oldInfo = ExaminationBLL.Get(info.Id);
                if (oldInfo == null)
                    return NotFound();
                oldInfo.Title = info.Title;
                oldInfo.StartTime = info.StartTime;
                oldInfo.EndTime = info.EndTime;
                oldInfo.ClassId = info.ClassId;
                oldInfo.YearId = info.YearId;
                oldInfo.CollegeIdFake = info.CollegeIdFake;
                oldInfo.DepartmentIdFake = info.DepartmentIdFake;
                oldInfo.SubjectIdFake = info.SubjectIdFake;
                if (ExaminationBLL.Edit(oldInfo))
                {
                    SetHighLineMsg("编辑成功.");
                    return PartialView(oldInfo);
                }
                SetHighLineMsg("未知错误.");
                return PartialView(oldInfo);
            }
            info.AddTime = DateTime.Now;
            info.IsTimeLimit = true;
            info.Type = 4;
            info.Title = info.Title;
            info.StartTime = info.StartTime;
            info.EndTime = info.EndTime;
            info.ClassId = info.ClassId;
            info.YearId = info.YearId;
            info.LimitTime = 0;
            if (ExaminationBLL.Add(info))
            {
                SetHighLineMsg("添加成功.");
                return PartialView(info);
            }
            SetHighLineMsg("未知错误.");
            return PartialView();
        }

        public ActionResult StudentListUc(int? pid, int? collegeIdSearch, int? departIdSearch, int? subjectIdSearch, int? classIdSearch, string uidSearch, string nameSearch, int? yearIdSearch, int? isScore)
        {
            CommonRequest.ClearCache();
            var list = StudentBLL.GetList(collegeIdSearch.CheckInt(0), departIdSearch.CheckInt(0), subjectIdSearch.CheckInt(0), classIdSearch.CheckInt(0), yearIdSearch.CheckInt(0), uidSearch, nameSearch, isScore.CheckInt(-1), 1).OrderByDescending(o => o.Id);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView(model);
        }
        [UrlStatFilter]
        public ActionResult Student()
        {
            return View();
        }

        public ActionResult StudentEditUc(int id)
        {
            var info = StudentBLL.Get(id);
            if (info == null)
                return NotFound();
            return PartialView(info);
        }

        [HttpPost]
        public ActionResult StudentEditUc(int id, string comment)
        {
            var info = StudentBLL.Get(id);
            if (info == null)
                return NotFound();
            ViewData.Model = info;
            if (string.IsNullOrEmpty(comment))
            {
                ModelState.AddModelError("Comment", "必须填写");
                return PartialView();
            }
            info.Comment = comment;
            if (StudentBLL.Edit(info))
            {
                SetHighLineMsg("评语成功.");
                return PartialView();
            }
            SetHighLineMsg("未知错误.");
            return PartialView();
        }

        public ActionResult StudentViewUc(int id)
        {
            var info = StudentBLL.Get(id);
            if (info == null)
                return NotFound();
            ViewData.Model = info;
            return PartialView();
        }

        public ActionResult ExaminationDel(int id)
        {
            var info = ExaminationBLL.Get(id);
            if (ExaminationBLL.Del(id))
            {

                SetAlertMsg("删除成功.", true);
                return RedirectToAction("Examination", new { type = info.Type });
            }
            return RedirectToAction("Examination", new { type = 0 });
        }
        [UrlStatFilter]
        public ActionResult SectionTest(int? sectionId)
        {
            var type = 0;
            if (Request["set0"] != null)
                type = 0;
            else if (Request["set1"] != null)
                type = 1;
            else if (Request["set2"] != null)
                type = 2;
            else if (Request["set3"] != null)
                type = 3;
            ViewData["type"] = type;
            if (type < 2)
            {
                var info = SectionBLL.Get(sectionId);
                if (info == null)
                    return NotFound();
                ViewData["ChapterId"] = info.ChapterId;
                ViewData["SectionId"] = info.Id;
            }
            return View();
        }

        private string GetExaminationTitleByType(int type)
        {
            switch (type)
            {
                case 0:
                    return "章节练习"; break;
                case 1:
                    return "章节作业"; break;
                case 2:
                    return "课程练习"; break;
                case 3:
                    return "课程作业"; break;
            }
            return "";
        }

        public ActionResult SectionListUc(int sectionId, int type)
        {
            CommonRequest.ClearCache();
            ExaminationInfo reInfo = null;
            if (type < 2)
            {
                reInfo = ExaminationBLL.GetList(type, sectionId).FirstOrDefault();
            }
            else
            {
                sectionId = 0;
                reInfo = ExaminationBLL.GetList(type, 0).FirstOrDefault();
            }
            if (reInfo == null)
            {
                var add = new ExaminationInfo
                {
                    AddTime = DateTime.Now,
                    IsTimeLimit = false,
                    EndTime = DateTime.Now.AddDays(5),
                    LimitTime = 120,
                    Status = 1,
                    SectionId = sectionId,
                    Type = type,
                    Title = GetExaminationTitleByType(type)
                };
                if (!ExaminationBLL.Add(add))
                {
                    return NotFound();
                }
                reInfo = add;
            }
            ViewData["type"] = type;
            return PartialView(reInfo);
        }

        public ActionResult ExaminationItem(int eid, int type)
        {
            var info = ExaminationBLL.Get(eid);
            if (info == null)
                return NotFound();
            ViewData["type"] = type;
            return View(info);
        }
        [UrlStatFilter]
        public ActionResult Examination(int? type, int? sectionId)
        {
            type = type.CheckInt(0);
            switch (type)
            {
                case 0:
                    return RedirectToAction("SectionTest", new { sectionId, set0 = "1" });
                case 1:
                    return RedirectToAction("SectionTest", new { sectionId, set1 = "1" });
                case 2:
                    return RedirectToAction("SectionTest", new { sectionId, set2 = "1" });
                case 3:
                    return RedirectToAction("SectionTest", new { sectionId, set3 = "1" });
                case 4:
                    return View();

            }
            return NotFound();
        }

        public ActionResult ExamResultListUc(int? pid, int? type, string title)
        {
            type = type.CheckInt(-1);
            CommonRequest.ClearCache();
            var list = ExaminationBLL.GetNotTypeList(type.Value, title).OrderByDescending(o => o.Id);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView(model);
        }

        public ActionResult Examination1ListUc(int? pid, int type)
        {
            CommonRequest.ClearCache();
            var list = ExaminationBLL.GetList(type).OrderByDescending(o => o.Id);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView(model);
        }

        public ActionResult ExaminationListUc(int? pid, int? collegeIdSearch, int? departIdSearch, int? subjectIdSearch, int? classIdSearch, int? yearIdSearch)
        {
            CommonRequest.ClearCache();
            var list = ExaminationBLL.GetList(collegeIdSearch.CheckInt(0), departIdSearch.CheckInt(0), subjectIdSearch.CheckInt(0), classIdSearch.CheckInt(0), yearIdSearch.CheckInt(0)).OrderByDescending(o => o.Id);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView(model);
        }
        [UrlStatFilter]
        public ActionResult Scoring()
        {
            return View();
        }

        public ActionResult ScoringListUc(int? pid, int? type, string title, string student, int? isScoring)
        {
            type = type.CheckInt(-1);
            isScoring = isScoring.CheckInt(-1);
            CommonRequest.ClearCache();
            var list = ExamSummaryBLL.GetList(type.Value, title, student, isScoring.Value);
            if (type.Value == 4)
                list = list.Where(o => o.IsCommit);
            var model = list.OrderByDescending(o => o.Id).ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView(model);
        }

        public ActionResult ExamReview(int id)
        {
            var info = ExamSummaryBLL.Get(id);
            if (info == null)
                return NotFound();
            return View(info);
        }

        [HttpPost]
        public ActionResult ExamReviewSave(int id)
        {
            var info = ExamSummaryBLL.Get(id);
            if (info == null)
                return NotFound();
            var examInfo = info.ExaminationInfo;
            var stuKeyList = examInfo.ExamAnswerInfo.Where(o => o.Uid == info.StudentInfo.Id).ToList();
            foreach (var item in stuKeyList)
            {
                item.Comment = Request["comment" + item.Id].CheckStr("");
                if (item.QuestionLibInfo.Type == 3 || item.QuestionLibInfo.Type == 4)
                {
                    item.Score = Request["score" + item.Id].CheckInt(0);
                }
            }
            var reMsg = "保存成功.";
            if (Request["Submit"] != null)
            {
                info.IsScoring = true;
                info.Score = stuKeyList.Sum(o => o.Score);
                reMsg = "提交成功.";
            }
            if (ExamSummaryBLL.Edit(info) && ExamAnswerBLL.Edit(stuKeyList))
            {
                SetAlertMsg(reMsg, true);
            }
            else
            {
                SetAlertMsg("未知错误.", true);
            }
            return RedirectToAction("ExamReview", new { id });
        }
        public ActionResult LibSelectItemList(int eid, int type, string search)
        {
            var info = ExaminationBLL.Get(eid);
            if (info == null)
                return NotFound();
            ViewData["Eid"] = eid;
            ViewData["Type"] = type;
            return View();
        }
        public ActionResult LibSelectItemListUc(int? pid, int eid, int type, string search)
        {
            var info = ExaminationBLL.Get(eid);
            if (info == null)
                return NotFound();
            CommonRequest.ClearCache();
            var list = QuestionLibBLL.GetList(search, info.SectionId, type, -1, -1).OrderByDescending(o => o.Id);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            ViewData["examInfo"] = info;
            return PartialView(model);
        }

        public ActionResult ExaminationItemScoreEditUc(int id)
        {
            var info = ExaminationItemBLL.Get(id);
            if (info == null)
                return NotFound();
            return PartialView(info);
        }

        [HttpPost]
        public ActionResult ExaminationItemScoreEditUc(ExaminationItemInfo info)
        {
            if (info.Id == 0)
                return NotFound();
            // if (info.Score <= 0)
            {
                ModelState.AddModelError("Score", "请输入大于0的整数");
                return PartialView();
            }
            var oldInfo = ExaminationItemBLL.Get(info.Id);
            if (oldInfo == null)
                return NotFound();
            //oldInfo.Score = info.Score;
            if (ExaminationItemBLL.Edit(oldInfo))
            {
                ExaminationBLL.UpdateExaminationScore(oldInfo.Eid);
                SetHighLineMsg("编辑成功.");
                return PartialView(oldInfo);
            }
            SetHighLineMsg("未知错误.");
            return PartialView();
        }

        public ActionResult ExaminationItemListUc(int? pid, int eid, int type)
        {
            CommonRequest.ClearCache();
            var list = ExaminationItemBLL.GetList(eid, type);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView(model);
        }

        public ActionResult ExaminationItemDel(int id)
        {
            var info = ExaminationItemBLL.Get(id);
            if (info == null)
                return NotFound();
            if (ExaminationItemBLL.Del(id))
            {
                ExaminationBLL.UpdateExaminationScore(info.Eid);
                //如果是考试类型，检测是否需要取消发布
                if (info.ExaminationInfo.Type == 4)
                {
                    var infoHost = ExaminationBLL.Get(info.Eid);
                    if (infoHost == null)
                        return NotFound();
                    if (infoHost.Score != 100)
                    {
                        infoHost.Status = 0;
                        ExaminationBLL.Edit(infoHost);
                    }
                }
                SetAlertMsg("删除成功.", true);
            }
            return RedirectToAction("ExaminationItem", new { eid = id, type = info.QuestionLibInfo.Type });
        }

        public ActionResult ExaminationItemSelect(int eid, int sid)
        {
            var info = ExaminationBLL.Get(eid);
            if (info == null)
                return NotFound();

            var qInfo = QuestionLibBLL.Get(sid);
            if (qInfo == null)
                return NotFound();
            if (info.ExaminationItemInfo.FirstOrDefault(o => o.Eid == eid && o.Qid == sid) != null)
            {
                SetAlertMsg("不能重复添加相同项!", true);
                return RedirectToAction("ExaminationItem", new { eid, type = qInfo.Type });
            }
            var add = new ExaminationItemInfo { Eid = eid, Qid = sid };
            if (!ExaminationItemBLL.Add(add))
            {
                return NotFound();
            }
            qInfo.UseTimes++;
            QuestionLibBLL.Edit(qInfo);
            //if (add.ExaminationInfo.Type == 4)
            ExaminationBLL.UpdateExaminationScore(add.Eid);
            return RedirectToAction("ExaminationItem", new { eid = eid, type = qInfo.Type });
        }

        public ActionResult ExaminationUpdateScore(int id)
        {
            var info = ExaminationBLL.Get(id);
            if (info == null)
                return NotFound();
            var re = ExaminationBLL.UpdateExaminationScore(id);
            if (re)
                SetAlertMsg("更新成功.", true);
            return RedirectToAction("Examination", new { info.Type, info.SectionId });
        }

        public ActionResult ExaminationPub(int id)
        {
            var info = ExaminationBLL.Get(id);
            if (info == null)
                return NotFound();
            if (info.Status == 0)
            {
                if (info.Score != 100)
                {
                    SetAlertMsg("该考试总分不等于100分不能发布!", true);
                    return RedirectToAction("Examination", new { type = 4 });
                }
                info.Status = 1;
            }
            else
                info.Status = 0;
            if (ExaminationBLL.Edit(info))
            {
                SetAlertMsg("设置成功.", true);
            }
            return RedirectToAction("Examination", new { info.Type });
        }

        public ActionResult ExaminationExport(int id)
        {
            CommonRequest.ClearCache();
            var info = ExaminationBLL.Get(id);
            var sb = new StringBuilder(1000);
            sb.AppendLine("序号,学号,姓名,学院,系别,专业,班别,年级,考试,成绩");
            int i = 1;
            foreach (var item in info.ExamSummaryInfo)
            {
                sb.AppendLine((i++) + "," + item.Uid + "," +
                              item.StudentInfo.StuName
                              + "," +
                              item.StudentInfo.ClassInfo.SubjectInfo.DepartmentInfo.CollegeInfo.Name + "," +
                              item.StudentInfo.ClassInfo.SubjectInfo.DepartmentInfo.Name + "," + item.StudentInfo.ClassInfo.SubjectInfo.Name
                              + "," +
                              item.StudentInfo.ClassInfo.ClassName + "," + item.StudentInfo.GradeYearInfo.Year + "," + info.Title + "," + item.Score);
            }
            string filename = string.Format("{1}_{0:yyyyMMdd_hhmmss}.csv", DateTime.Now, info.Title + "成绩");
            byte[] buffer = Encoding.Default.GetBytes(sb.ToString());
            var outPutStream = new MemoryStream(buffer) { Position = 0 };
            return File(outPutStream, "text/csv", HttpUtility.UrlEncode(filename));
        }

        public ActionResult SetExcellent(int id)
        {
            var info = ExamSummaryBLL.Get(id);
            if (info == null)
                return NotFound();
            info.IsExcellent = !info.IsExcellent;
            if (ExamSummaryBLL.Edit(info))
                SetAlertMsg("设置成功.", true);
            return RedirectToAction("Scoring");
        }

        public ActionResult ExaminationScorePub(int id)
        {
            var info = ExaminationBLL.Get(id);
            if (info == null)
                return NotFound();
            // info.IsPubScore = !info.IsPubScore;
            if (ExaminationBLL.Edit(info))
            {
                SetAlertMsg("设置成功.", true);
            }
            return RedirectToAction("ExamResult");
        }
        [UrlStatFilter]
        public ActionResult ExamResult()
        {
            return View();
        }

        public ActionResult LibEditUc(int? id)
        {
            if (id.HasValue)
            {
                var oldInfo = QuestionLibBLL.Get(id.Value);
                if (oldInfo == null)
                    return NotFound();
                return PartialView(oldInfo);
            }
            return PartialView(new QuestionLibInfo { });
        }

        public ActionResult LibDel(int id)
        {
            var toUpdateScoreList = ExaminationBLL.GetListByLibId(id);
            if (QuestionLibBLL.Del(id))
            {
                ExamLibHelper.ChangeItemScoreByDel(toUpdateScoreList.Select(o => o.Id).ToArray());
                SetAlertMsg("删除成功!", true);
            }
            return RedirectToAction("Lib");
        }

        public ActionResult AnswerEdit(int id, int? fromId)
        {
            var info = QuestionLibBLL.Get(id);
            if (info == null)
                return NotFound();
            switch (info.Type)
            {
                case 0:
                    return RedirectToAction("OneChoices", new { id, fromId });
                case 1:
                    return RedirectToAction("RadioChoices", new { id, fromId });
                case 2:
                    return RedirectToAction("Judge", new { id, fromId });
                case 3:
                case 4:
                    return RedirectToAction("QuestionAns", new { id, fromId });
            }
            return NotFound();
        }

        public ActionResult Judge(int id, int? fromId)
        {
            fromId = fromId.CheckInt(0);
            ViewData["fromId"] = fromId;
            var info = QuestionLibBLL.Get(id);
            if (info == null)
                return NotFound();
            return View(info);
        }
        public ActionResult QuestionAns(int id, int? fromId)
        {
            fromId = fromId.CheckInt(0);
            ViewData["fromId"] = fromId;
            var info = QuestionLibBLL.Get(id);
            if (info == null)
                return NotFound();
            return View(info);
        }
        public ActionResult JudgeAnsEditUc(int qid)
        {
            var info = QuestionLibBLL.Get(qid);
            if (info == null)
            {
                return NotFound();
            }
            if (info.QuestionAnswerInfo == null)
            {
                var addInfo = new QuestionAnswerInfo { Qid = qid, Answer = "" };
                if (!QuestionAnswerBLL.Add(addInfo))
                    return NotFound();
                return PartialView(addInfo);
            }
            return PartialView(info.QuestionAnswerInfo);
        }

        [HttpPost]
        public ActionResult JudgeAnsEditUc(QuestionAnswerInfo info)
        {
            ViewData.Model = info;
            var isTrue = Request["isTrue"];
            if (info.Id == 0)
                return NotFound();
            var oldInfo = QuestionAnswerBLL.Get(info.Id);
            if (oldInfo == null)
                return NotFound();
            oldInfo.Answer = isTrue == "true,false" ? "" : "1";
            if (QuestionAnswerBLL.Edit(oldInfo))
            {
                SetHighLineMsg("编辑成功.");
                return PartialView(oldInfo);
            }
            SetHighLineMsg("未知错误.");
            return PartialView();
        }
        public ActionResult AnsEditUc(int qid)
        {
            var info = QuestionLibBLL.Get(qid);
            if (info == null)
            {
                return NotFound();
            }
            if (info.QuestionAnswerInfo == null)
            {
                var addInfo = new QuestionAnswerInfo { Qid = qid, Answer = "" };
                if (!QuestionAnswerBLL.Add(addInfo))
                    return NotFound();
                return PartialView(addInfo);
            }
            return PartialView(info.QuestionAnswerInfo);
        }

        [HttpPost]
        public ActionResult AnsEditUc(QuestionAnswerInfo info)
        {
            ViewData.Model = info;
            if (!ModelState.IsValid)
                return PartialView();
            if (info.Id == 0)
                return NotFound();
            var oldInfo = QuestionAnswerBLL.Get(info.Id);
            if (oldInfo == null)
                return NotFound();
            oldInfo.Answer = info.Answer;
            if (QuestionAnswerBLL.Edit(oldInfo))
            {
                SetHighLineMsg("编辑成功.");
                return PartialView(oldInfo);
            }
            SetHighLineMsg("未知错误.");
            return PartialView();
        }

        public ActionResult RadioChoices(int id, int? fromId)
        {
            fromId = fromId.CheckInt(0);
            var info = QuestionLibBLL.Get(id);
            if (info == null)
                return NotFound();
            ViewData["fromId"] = fromId;
            return View(info);
        }

        [HttpPost]
        public ActionResult RadioChoices(int id)
        {
            var fromId = Request["fromId"].CheckInt(0);
            var info = QuestionLibBLL.Get(id);
            if (info == null)
                return NotFound();
            if (Request["txtTitle"] == null)
            {
                if (RadioChoicesBLL.DelByRid(id))
                    SetAlertMsg("保存成功.");
                else
                    SetAlertMsg("未知错误.");

                ViewData["fromId"] = fromId;
                return View(info);
            }
            var titleArry = Request["txtTitle"].Split(',');
            var chkArry = Request["chkAll"].Split(',');
            var hidIdArry = Request["hidId"].Split(',');
            var list = new List<RadioChoicesInfo>();
            for (var i = 0; i < titleArry.Length; i++)
            {
                var item = titleArry[i];
                if (string.IsNullOrEmpty(item))
                    continue;
                list.Add(new RadioChoicesInfo { Id = hidIdArry[i].CheckInt(0), Title = item, Rid = id, IsAnswer = chkArry[i] == "true" });
            }
            if (RadioChoicesBLL.UpdateOrAdd(id, list))
                SetAlertMsg("保存成功.");
            else
                SetAlertMsg("未知错误.");

            ViewData["fromId"] = fromId;
            info = QuestionLibBLL.Get(id);
            return View(info);
        }


        public ActionResult OneChoices(int id, int? fromId)
        {
            fromId = fromId.CheckInt(0);
            var info = QuestionLibBLL.Get(id);
            if (info == null)
                return NotFound();
            ViewData["fromId"] = fromId;
            return View(info);
        }

        [HttpPost]
        public ActionResult OneChoices(int id)
        {
            var fromId = Request["fromId"].CheckInt(0);
            var info = QuestionLibBLL.Get(id);
            if (info == null)
                return NotFound();
            if (Request["txtTitle"] == null)
            {
                if (RadioChoicesBLL.DelByRid(id))
                    SetAlertMsg("保存成功.");
                else
                    SetAlertMsg("未知错误.");

                ViewData["fromId"] = fromId;
                return View(info);
            }
            var titleArry = Request["txtTitle"].Split(',');
            var chkArry = Request["chkAll"].Split(',');
            var hidIdArry = Request["hidId"].Split(',');
            var list = new List<RadioChoicesInfo>();
            for (var i = 0; i < titleArry.Length; i++)
            {
                var item = titleArry[i];
                if (string.IsNullOrEmpty(item))
                    continue;
                list.Add(new RadioChoicesInfo { Id = hidIdArry[i].CheckInt(0), Title = item, Rid = id, IsAnswer = chkArry[i] == "true" });
            }
            if (RadioChoicesBLL.UpdateOrAdd(id, list))
                SetAlertMsg("保存成功.");
            else
                SetAlertMsg("未知错误.");

            ViewData["fromId"] = fromId;
            info = QuestionLibBLL.Get(id);
            return View(info);
        }



        public ActionResult ChoicesListUc(int? pid, int rid)
        {
            CommonRequest.ClearCache();
            var info = QuestionLibBLL.Get(rid);
            var list = RadioChoicesBLL.GetList(rid);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            ViewData["Rid"] = rid;
            if (info.Type == 0)
                return PartialView("OneChoicesListUc", model);
            return PartialView(model);
        }

        public ActionResult ChoicesEditUc(int? id, int? rid)
        {
            if (id.HasValue)
            {
                var oldInfo = RadioChoicesBLL.Get(id.Value);
                if (oldInfo == null)
                    return NotFound();
                return PartialView(oldInfo);
            }
            if (!rid.HasValue)
                return NotFound();
            return PartialView(new RadioChoicesInfo { Rid = rid.Value });
        }

        public ActionResult ExamDoView(int id)
        {
            var info = ExaminationBLL.Get(id);
            if (info == null)
            {
                SetErrorMsg("参数错误.");
                return NotFound();
            }
            return View(info);
        }

        public ActionResult ChoicesDel(int id)
        {
            var info = RadioChoicesBLL.Get(id);
            if (info != null && RadioChoicesBLL.Del(id))
            {
                SetAlertMsg("删除成功.", true);
                return RedirectToAction("RadioChoices", new { id = info.Rid });
            }
            return NotFound();
        }

        [HttpPost]
        public ActionResult ChoicesEditUc(RadioChoicesInfo info)
        {
            ViewData.Model = info;
            if (!ModelState.IsValid)
                return PartialView();
            if (info.Id != 0)
            {
                var oldInfo = RadioChoicesBLL.Get(info.Id);
                if (oldInfo == null)
                    return NotFound();
                oldInfo.Title = info.Title;
                oldInfo.IsAnswer = info.IsAnswer;
                if (RadioChoicesBLL.Edit(oldInfo))
                {
                    //如果是单选题设置了答案,则清除之前设置的答案
                    if (oldInfo.IsAnswer && oldInfo.QuestionLibInfo.Type == 0)
                    {
                        RadioChoicesBLL.SetRadioKey(oldInfo.Rid, oldInfo.Id);
                    }
                    SetHighLineMsg("编辑成功.");
                    return PartialView(oldInfo);
                }
                SetHighLineMsg("未知错误.");
                return PartialView();
            }
            var addInfo = new RadioChoicesInfo
            {
                IsAnswer = info.IsAnswer,
                Rid = info.Rid,
                Title = info.Title
            };
            if (RadioChoicesBLL.Add(addInfo))
            {
                //如果是单选题设置了答案,则清除之前设置的答案
                if (addInfo.IsAnswer && addInfo.QuestionLibInfo.Type == 0)
                {
                    RadioChoicesBLL.SetRadioKey(addInfo.Rid, addInfo.Id);
                }
                SetHighLineMsg("添加成功.");
                return PartialView(addInfo);
            }
            SetHighLineMsg("未知错误.");
            return PartialView();
        }

        [HttpPost]
        public ActionResult LibEditUc(QuestionLibInfo info)
        {
            ViewData["jump"] = Request["jump"].CheckStr("");
            ViewData.Model = info;
            if (!ModelState.IsValid)
                return PartialView();
            if (info.Id != 0)
            {
                var oldInfo = QuestionLibBLL.Get(info.Id);
                if (oldInfo == null)
                    return NotFound();
                oldInfo.Title = info.Title;
                oldInfo.Keyword = info.Keyword ?? "";
                oldInfo.DiffCoe = info.DiffCoe;
                oldInfo.Score = info.Score;
                if (QuestionLibBLL.Edit(oldInfo))
                {
                    ExamLibHelper.ChangeItemScore(oldInfo.Id);
                    SetHighLineMsg("编辑成功.");
                    return PartialView(oldInfo);
                }
                SetHighLineMsg("未知错误.");
                return PartialView();
            }
            //新添加需要对章节校验
            if (info.SectionId == -1 || info.SectionId == 0)
            {
                ModelState.AddModelError("SectionId", "请选择所属章节");
                return PartialView();
            }
            var addInfo = new QuestionLibInfo
                              {
                                  AddTime = DateTime.Now,
                                  SectionId = info.SectionId,
                                  Score = info.Score,
                                  DiffCoe = info.DiffCoe,
                                  Keyword = info.Keyword ?? "",
                                  Title = info.Title,
                                  Type = info.Type,
                                  UseTimes = 0
                              };
            //当判断题时,空代表正确.
            if (info.Type >= 2 && info.Type <= 4)
            {
                addInfo.QuestionAnswerInfo = new QuestionAnswerInfo { Qid = info.Id, Answer = "" };
            }
            if (QuestionLibBLL.Add(addInfo))
            {
                SetHighLineMsg("添加成功.");
                ViewData["jump"] = addInfo.Id;
                return PartialView(addInfo);
            }
            SetHighLineMsg("未知错误.");
            return PartialView();
        }

        public ActionResult LibListUc(int? pid, string search, int? sectionIdSearch, int? ddlQtType, double? ddlMinDiff, double? ddlMaxDiff)
        {
            CommonRequest.ClearCache();
            sectionIdSearch = sectionIdSearch.CheckInt(0);
            ddlQtType = ddlQtType.CheckInt(-1);
            ddlMinDiff = ddlMinDiff.CheckDouble(-1);
            ddlMaxDiff = ddlMaxDiff.CheckDouble(-1);
            var list = QuestionLibBLL.GetList(search, sectionIdSearch.Value, ddlQtType.Value, ddlMinDiff.Value, ddlMaxDiff.Value).OrderByDescending(o => o.Id);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView(model);
        }

        public ActionResult ExamLib()
        {
            return View();
        }

        public ActionResult ExamLibListUc(int? pid)
        {
            CommonRequest.ClearCache();
            var list = ExamLibBLL.GetList().OrderByDescending(o => o.Id);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView(model);
        }

        public ActionResult ExamLibEditUc(int? id)
        {
            if (id.HasValue)
            {
                var oldInfo = ExamLibBLL.Get(id.Value);
                if (oldInfo == null)
                    return NotFound();
                return PartialView(oldInfo);
            }
            return PartialView(new ExamLibInfo { Title = "" });
        }

        [HttpPost]
        public ActionResult ExamLibEditUc(ExamLibInfo info)
        {
            ViewData.Model = info;
            if (ExamLibBLL.IsExist(info.Title, info.Id))
            {
                ModelState.AddModelError("Title", "已经存在相同题库名称.");
            }
            if (!ModelState.IsValid)
                return PartialView();

            if (info.Id != 0)
            {
                var oldInfo = ExamLibBLL.Get(info.Id);
                if (oldInfo == null)
                    return NotFound();
                oldInfo.Title = info.Title;
                if (ExamLibBLL.Edit(oldInfo))
                {
                    SetHighLineMsg("编辑成功.");
                    return PartialView(oldInfo);
                }
                SetHighLineMsg("未知错误.");
                return PartialView();
            }
            if (ExamLibBLL.Add(info))
            {
                SetHighLineMsg("添加成功.");
                return PartialView();
            }
            SetHighLineMsg("未知错误.");
            return PartialView();
        }

        public ActionResult ExamLibDel(int id)
        {
            if (ExamLibBLL.Del(id))
            {
                SetAlertMsg("删除成功.", true);
            }
            return RedirectToAction("ExamLib");
        }
    }
}
